package com.boarsoft.boar.soagov.batch.health;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.boar.entity.ObjLabel;
import com.boarsoft.boar.service.AppService;
import com.boarsoft.boar.service.ObjLabelService;
import com.boarsoft.flow.core.bean.ForkHandler;

/**
 * 并行检测N个实例
 * 
 * @author Mac_J
 *
 */
public class HealthChkAppFH implements ForkHandler {
	private static final Logger log = LoggerFactory.getLogger(HealthChkAppFH.class);

	@Autowired
	protected AppService appSvc;
	@Autowired
	protected ObjLabelService objLabelSvc;

	/** 最多线程数 */
	protected int maxThreads = 5;

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, Object> fork(String key, Object data, Throwable throwable) {
		Map<String, String> map = (Map<String, String>) data;
		// 只有部分应用需要依赖此批量来做健康检查
		List<ObjLabel> oLt = objLabelSvc.list(//
				ObjLabel.TYPE_APP, map.get("key"), map.get("value"));
		Map<String, Object> rm = new HashMap<>();
		int i = 0, j = 0, //
				tt = oLt.size(), // 总实例数
				ts = Math.min(tt, maxThreads); // 最大线程数
		List<Map<String, Object>> lt = null;
		for (ObjLabel o : oLt) {
			String appId = o.getObjId();
			String handler = appSvc.getHandler(appId);
			if (i++ % ts == 0) {
				lt = new ArrayList<>();
				rm.put(String.valueOf(j++), lt);
			}
			Map<String, Object> m = new HashMap<>();
			m.put("appId", appId);
			m.put("handler", handler);
			m.put("env", map.get("env"));
			m.put("group", map.get("group"));
			lt.add(m);
		}
		log.info("Fork result = {}", rm);
		return rm;
	}

	public int getMaxThreads() {
		return maxThreads;
	}

	public void setMaxThreads(int maxThreads) {
		this.maxThreads = maxThreads;
	}
}